package com.aun.hockey.server;

import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * This class provides a service to send emails.
 * 
 * @author ssommer
 */
public class EmailService {

	private Properties props;
	private String senderAddress;

	public EmailService() {
		ResourceBundle bundle = ResourceBundle.getBundle("mail");

		senderAddress = bundle.getString("mail.from");

		props = new Properties();
		props.put("mail.smtp.host", bundle.getString("mail.server"));
	}

	/**
	 * Sends an email to given recipients.
	 * 
	 * @param recipient
	 * @param subject
	 * @param text
	 * @throws MessagingException
	 */
	public void sendEmail(InternetAddress[] recipients, String subject, String text) throws MessagingException {

		Session session = Session.getInstance(props, null);

		MimeBodyPart bodyPart = new MimeBodyPart();
		bodyPart.setText(text);

		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(bodyPart);

		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(senderAddress));
		message.setRecipients(Message.RecipientType.TO, recipients);
		message.setSubject(subject);
		message.setSentDate(new Date());
		message.setContent(multipart);

		Transport.send(message);
	}

}
